package com.example.japinhands.ui

import android.content.Context
import androidx.activity.compose.BackHandler
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.BottomNavigation
import androidx.compose.material.BottomNavigationItem
import androidx.compose.material.ButtonDefaults
import androidx.compose.material.ExperimentalMaterialApi
import androidx.compose.material.ListItem
import androidx.compose.material.Scaffold
import androidx.compose.material.ScaffoldState
import androidx.compose.material.TextButton
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Favorite
import androidx.compose.material.icons.filled.Home
import androidx.compose.material.icons.filled.Menu
import androidx.compose.material.icons.filled.Settings
import androidx.compose.material.rememberScaffoldState
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.unit.dp
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavController
import androidx.navigation.NavGraph.Companion.findStartDestination
import androidx.navigation.NavType
import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.rememberNavController
import androidx.navigation.navArgument
import com.example.japinhands.JapViewModel
import com.example.japinhands.R
import com.example.japinhands.data.DeformAdj
import com.example.japinhands.data.DeformVerb
import com.example.japinhands.data.Word
import com.example.japinhands.route.Route
import com.example.japinhands.ui.screen.ManageDeformAdjScreen
import com.example.japinhands.ui.screen.ManageSentenceScreen
import com.example.japinhands.ui.screen.ManageWordScreen
import com.example.japinhands.ui.screen.DeformAdjScreen
import com.example.japinhands.ui.screen.DeformVerbScreen
import com.example.japinhands.ui.screen.TestManageWordScreen
import com.example.japinhands.ui.screen.TestNewSentenceScreen
import com.example.japinhands.ui.screen.TestScreen
import com.example.japinhands.ui.screen.TestUpdateWordScreen
import com.example.japinhands.ui.screen.TestWordDetailScreen
import com.example.japinhands.ui.screen.newword.WordScreen
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun JapScaffold(
    context: Context
) {

    val scaffoldState = rememberScaffoldState()
    val scope = rememberCoroutineScope()
    val navController = rememberNavController()

    var selectedItem by remember { mutableStateOf(0) }
    val items = listOf("ついか", "かんり", "せってい")
    val sharedViewModel: JapViewModel = viewModel(
//        factory = WordViewModelFactory(
//            wordDao = WordDatabase.getDatabase(context = context).wordDao(),
//            adjDao = WordDatabase.getDatabase(context = context).adjDao(),
//            verbDao = WordDatabase.getDatabase(context = context).verbDao(),
//            sentenceDao = WordDatabase.getDatabase(context = context).sentenceDao()
//        )
    )




    Scaffold(
        scaffoldState = scaffoldState,
        topBar = {
            TopAppBar(
                navigationIcon = {
                    IconButton(
                        onClick = {
                            scope.launch {
                                scaffoldState.drawerState.open()
                            }
                        }
                    ) {
                        Icon(Icons.Filled.Menu, null)
                    }
                },
                title = {
                    Text("Jap In Hands")
                }
            )
        },
        bottomBar = {
            BottomNavigation(
//                modifier = Modifier.border(1.dp, Color.Gray),
                backgroundColor = Color(0xFF333333),
                contentColor = MaterialTheme.colorScheme.onBackground,
                elevation = 10.dp
            ) {
                items.forEachIndexed { index, item ->
                    BottomNavigationItem(
                        icon = {
                            when(index){
                                0 -> Icon(Icons.Filled.Home, contentDescription = null)
                                1 -> Icon(Icons.Filled.Favorite, contentDescription = null)
                                else -> Icon(Icons.Filled.Settings, contentDescription = null)
                            }
                        },
                        label = { Text(item) },
                        selected = selectedItem == index,
                        onClick = {
                            selectedItem = index
                            when (index) {
                                0 -> navController.navigate(Route.NewWord.route) {
                                    popUpTo(navController.graph.findStartDestination().id) {
                                        saveState = true
                                    }
                                    launchSingleTop = true
                                    restoreState = true
                                }
                                1 -> navController.navigate(Route.ManageWord.route) {
                                    popUpTo(navController.graph.findStartDestination().id) {
                                        saveState = true
                                    }
                                    launchSingleTop = true
                                    restoreState = true
                                }
                                else -> navController.navigate(Route.Test.route) {
                                    popUpTo(navController.graph.findStartDestination().id) {
                                        saveState = true
                                    }
                                    launchSingleTop = true
                                    restoreState = true
                                }
                            }
                        }
                    )
                }
            }
        },
        backgroundColor = MaterialTheme.colorScheme.background,
        contentColor = MaterialTheme.colorScheme.primary,
        drawerContent = {
            AppDrawerContent(scaffoldState, scope, navController)
        }
    ) { paddingValues ->
        NavHost(
            navController = navController,
            startDestination = Route.Home.route,
            modifier = Modifier.padding(paddingValues)
        ) {
            composable(route = Route.Home.route) {
                HomeScreen()
            }
            composable(route = Route.Test.route) {
                TestScreen(
                    navController = navController,
                    viewModel = sharedViewModel
                )
            }
            composable(route = Route.NewSentence.route) {
                TestNewSentenceScreen(
                    viewModel = sharedViewModel
                )
            }
            composable(route = Route.ManageSentence.route) {
                ManageSentenceScreen(
                    viewModel = sharedViewModel
                )
            }
            composable(route = Route.NewDeformVerb.route) {
                DeformVerbScreen(
                    viewModel = sharedViewModel,
                    update = false
                )
            }
            composable(route = Route.NewDeformAdj.route) {
                DeformAdjScreen(
                    viewModel = sharedViewModel,
                    update = false
                )
            }
            composable(route = Route.ManageDeformAdj.route) {
                ManageDeformAdjScreen(
                    viewModel = sharedViewModel
                )
            }
            composable(route = Route.NewWord.route) {
                WordScreen(
                    viewModel = sharedViewModel,
                    update = false
                )
            }
            composable(route = Route.TestManageWord.route) {
                TestManageWordScreen(viewModel = sharedViewModel)
            }
            composable(route = Route.ManageWord.route) {
                ManageWordScreen(
                    viewModel = sharedViewModel,
                    navController = navController
                )
            }
            composable(
                route = Route.WordDetail.route,
                arguments = listOf(
                    navArgument("wordId") {
                        type = NavType.LongType
                    }
                )
            ) { backStackEntry ->
//                val arguments = navController.previousBackStackEntry?.arguments
//                val word = arguments?.getParcelable(
//                    Route.WordDetail.route,
//                    Word::class.java
//                )
                var wordUI by remember {
                    mutableStateOf(Word())
                }
                var deformAdjUI by remember {
                    mutableStateOf(DeformAdj())
                }
                var deformVerbUI by remember {
                    mutableStateOf(DeformVerb())
                }
                LaunchedEffect(Unit) {
                    val wordId = backStackEntry.arguments?.getLong("wordId")
                    wordId?.let { id ->
                        sharedViewModel.queryWord(id) {
                            it?.let {
                                wordUI = it
                                sharedViewModel.queryDeformById(
                                    adjId = it.deformAdj,
                                    verbId = it.deformVerb,
                                    onGetAdj = { adj -> adj?.let { deformAdjUI = adj } },
                                    onGetVerb = { verb -> verb?.let { deformVerbUI = verb } }
                                )
                            }
                        }
                    }
                }
                TestWordDetailScreen(
                    word = wordUI,
                    adj = deformAdjUI,
                    verb = deformVerbUI,
                    navController = navController
                )
            }
            composable(
                route = Route.TestUpdateWord.route,
                arguments = listOf(
                    navArgument("wordId") {
                        type = NavType.LongType
                    }
                )
            ) { backStackEntry ->
                var wordUI by remember {
                    mutableStateOf(Word())
                }
                LaunchedEffect(Unit) {
                    val wordId = backStackEntry.arguments?.getLong("wordId")
                    wordId?.let { id ->
                        sharedViewModel.queryWord(id) { word ->
                            word?.let {
                                wordUI = it
                            }
                        }
                    }
                }
                TestUpdateWordScreen(viewModel = sharedViewModel, word = wordUI)
            }
            composable(
                route = Route.UpdateWord.route,
                arguments = listOf(
                    navArgument("wordId") {
                        type = NavType.LongType
                    }
                )
            ) { backstackEntry ->
                var wordUI by remember {
                    mutableStateOf(Word())
                }
                var deformAdjUI by remember {
                    mutableStateOf(DeformAdj())
                }
                var deformVerbUI by remember {
                    mutableStateOf(DeformVerb())
                }
                LaunchedEffect(Unit) {
                    val wordId = backstackEntry.arguments?.getLong("wordId")
                    wordId?.let { id ->
                        sharedViewModel.queryWord(id) { word ->
                            word?.let {
                                wordUI = it
                                sharedViewModel.queryDeformById(
                                    adjId = it.deformAdj,
                                    verbId = it.deformVerb,
                                    onGetAdj = { adj -> adj?.let { deformAdjUI = adj } },
                                    onGetVerb = { verb -> verb?.let { deformVerbUI = verb } }
                                )
                            }
                        }
                    }
                }
                WordScreen(
                    viewModel = sharedViewModel,
                    update = true,
                    word = wordUI,
                    adj = deformAdjUI,
                    verb = deformVerbUI
                )
            }
        }



//        AppContent(item = items[selectedItem])
    }



}

@Composable
fun AppContent(
    item: String
) {
    Box(
        modifier = Modifier.fillMaxSize(),
        contentAlignment = Alignment.Center
    ) {
        Text("当前界面是 $item")
    }
}

@OptIn(ExperimentalMaterialApi::class)
@Composable
fun AppDrawerContent(
    scaffoldState: ScaffoldState,
    scope: CoroutineScope,
    navController: NavController
) {
    Column(
        modifier = Modifier
            .background(color = MaterialTheme.colorScheme.background)
            .padding(top = 60.dp, bottom = 5.dp)
    ) {
        Box {
//        Image(
//            painter = painterResource(id = R.drawable.avator),
//            contentDescription = null
//        )
            Column(
                modifier = Modifier.padding(15.dp)
            ) {
                Image(
                    painter = painterResource(id = R.drawable.avator),
                    contentDescription = null,
                    modifier = Modifier
                        .clip(CircleShape)
                        .size(65.dp)
                        .border(BorderStroke(1.dp, Color.Gray), CircleShape)
                )
                Spacer(Modifier.padding(vertical = 8.dp))
                Text(
                    text = "原神，启动！",
                    style = MaterialTheme.typography.bodyMedium
                )
            }
        }

        ListItem(
            icon = {
                Icon(Icons.Filled.Home, null)
            },
            modifier = Modifier
                .clickable {
                    navController.navigate(Route.Home.route) {
                        popUpTo(navController.graph.findStartDestination().id) {
                            saveState = true
                        }
                        launchSingleTop = true
                        restoreState = true
                    }
                    scope.launch {
                        scaffoldState.drawerState.close()
                    }
                }
        ) {
            Text("首页")
        }

        Box(
            modifier = Modifier.fillMaxHeight(),
            contentAlignment= Alignment.BottomStart
        ) {
            TextButton(
                onClick = { /*TODO*/ },
                colors = ButtonDefaults.textButtonColors(contentColor = MaterialTheme.colorScheme.onSurface),
            ) {
                Icon(Icons.Filled.Settings, null)
                Text("设置")
            }
        }

        // 编写逻辑
        // 如果 drawer 已经展开了，那么点击返回键收起而不是直接退出 app

        BackHandler(enabled = scaffoldState.drawerState.isOpen) {
            scope.launch {
                scaffoldState.drawerState.close()
            }
        }
    }

}